import {PageContainer} from "@ant-design/pro-layout";
import ProCard from "@ant-design/pro-card";
import type {ProTableProps} from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import type {SysUserData, SysUserParams, SysUserAdd} from "@/pages/system/user/type";
import columns from "@/pages/system/user/list/config/columns";
import {Button, message, SelectProps, Space, Tag} from "antd";
import React, {useEffect, useRef, useState} from "react";
import type {ActionType} from "@ant-design/pro-table/lib/typing";
import {
  downloadSysUserExport,
  downloadSysUserExportTemplate,
  sysUserImport,
  sysUserUpdate,
  sysUserAdd,
  sysUserPageList,
  sysUserRemove
} from "@/services/system/user/api";
import {history} from "umi";
import type {OptionActions} from "@/type/type";
import Upload from "@/components/Upload";
import AddSysUser from "@/pages/system/user/list/components/AddSysUser";
import type {ProFormInstance} from "@ant-design/pro-form";
import {sysDictValuePageList} from "@/services/system/dict/value/api";
import {SysDictValueParams} from "@/pages/system/dict/value/type";
import {sysRolePageList} from "@/services/system/role/api";
import AuthWrapper from "@/components/AuthWrapper";

export default () => {

  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<(number | string)[]>([]);
  const [userStatusList, setStatusList] = useState<SelectProps["options"]>([])
  const [roleList, setRoleList] = useState<SelectProps["options"]>([])
  useEffect(() => {
    const params: SysDictValueParams = {
      dictTypeName: "user_status",
      pageNum: -1,
      pageSize: -1
    }

    sysDictValuePageList(params).then(res => {
      setStatusList(res.data.records.map(item => {
        return {
          // @ts-ignore
          label: <Tag color={item.color} bordered={false}>{item.desc}</Tag>,
          value: parseInt(item.value)
        }
      }))
    })
    sysRolePageList({pageSize: -1, pageNum: -1}).then(res => {
      const roleList = res.data.records.map(item => {
        return {
          // @ts-ignore
          label: <Tag color={item.color} bordered={false}>{item.roleName}</Tag>,
          value: item.id
        }
      })
      setRoleList(roleList)
    })
  }, [])
  const sysUserAddRef: React.MutableRefObject<ProFormInstance<SysUserAdd> | undefined> = useRef<ProFormInstance<SysUserAdd> | undefined>();
  // @ts-ignore
  const optionAction: OptionActions<SysUserAdd, SysUserData> = {
    import: {
      maxCount: 1,
      showUploadList: false,
      beforeUpload: (file) => {
        const formData = new FormData();
        formData.append('file', file);
        sysUserImport(formData).then((res) => {
          actionRef?.current?.reload();
        });
      }
    },
    edit(data) {
      // @ts-ignore
      sysUserUpdate(data).then(res => {
        message.success("编辑成功").then(res => {
        })
        setSelectedRowKeys([]);
        actionRef.current?.reload();
      });
    },
    editModal: (data: SysUserData, authorized: boolean) => {
      return {
        trigger: <Button disabled={!authorized} type="link" onClick={() => {
          sysUserAddRef.current?.setFieldsValue(data)
        }}>编辑</Button>,
        onFinish: async (formData) => {
          await sysUserAddRef.current?.validateFields().then(res => {
            const sysUser: any = {
              ...formData,
              id: data.id
            }
            sysUserUpdate(sysUser).then(res => {
              message.success("操作成功")
              sysUserAddRef.current?.resetFields();
              actionRef.current?.reload();
            })
          })
          return true
        },
        formRef: sysUserAddRef,
        title: "新增后台用户表",
      }
    },
    add() {
      history.push({
        pathname: "sys/user/add"
      })
    },
    addModal: (id, authorized) =>{
      return {
        trigger: <Button disabled={!authorized} type="primary">新增</Button>,
        onFinish: async (formData) => {
          await sysUserAddRef.current?.validateFields().then(res => {
            sysUserAdd(formData as SysUserAdd).then(res => {
              message.success("新增成功")
              sysUserAddRef.current?.resetFields();
              actionRef.current?.reload();
            })
          })
          return true
        },
        formRef: sysUserAddRef,
        title: "新增后台用户表",

      }
    },
    export() {
      downloadSysUserExport(selectedRowKeys).then(res => {
        message.success("导出成功").then(res => {
        })
        setSelectedRowKeys([]);

      })
    },
    remove(ids) {
      sysUserRemove([...ids, ...selectedRowKeys]).then(res => {
        message.success("删除成功").then(res => {

        })
        setSelectedRowKeys([]);
        actionRef.current?.reload();
      });
    },
    exportTemplate() {
      downloadSysUserExportTemplate().then(res => {
        message.success("下载成功").then(res => {
        })
      })
    }
  }

  // @ts-ignore

  const tableProps
    :
    ProTableProps<SysUserData, SysUserParams> = {
    rowSelection: {
      // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
      // selections: [],
    },
    tableAlertRender: ({selectedRowKeys, selectedRows, onCleanSelected}) => {
      setSelectedRowKeys(selectedRowKeys);
      return (
        <Space size={24}>
                      <span>
                          已选 {selectedRowKeys.length} 项
                          <a style={{marginInlineStart: 8}} onClick={onCleanSelected}>
                           取消选择
                         </a>
                      </span>
        </Space>
      );
    },
    tableAlertOptionRender: () => {
      return (
        <Space size={16}>
          <a onClick={() => optionAction.remove([])}>批量删除</a>
          <a onClick={() => optionAction.export()}>导出数据</a>
        </Space>
      );
    },
    tableStyle: {},
    size: "small",
    bordered: true,
    // @ts-ignore
    columns: columns(optionAction, userStatusList, roleList),
    request: async (params, sort, filter) => {
      //@ts-ignore
      return await sysUserPageList({...params, roleId: params?.role?.value}).then(res => {
        return {
          data: res.data.records,
          success: true,
          total: res.data.total
        }
      })
    },
    headerTitle: (
      <Space>
        <AuthWrapper authorize={"system:tool:gen"}>
          {/*// @ts-ignore*/}
          {(authorized: boolean) => <AddSysUser {...optionAction.addModal(0, authorized)}/>}
        </AuthWrapper>
        <AuthWrapper authorize={"system:tool:import"}>
          {(authorized: boolean) => <Upload {...optionAction.import} disabled={!authorized}></Upload>}
        </AuthWrapper>
        <Button type="primary" onClick={() => optionAction.export()}>导出</Button>
        <Button type="primary" onClick={() => optionAction.exportTemplate()}>导出模版</Button>
      </Space>
    ),
    actionRef,
    rowKey: "id"
  }
  return (
    <PageContainer>
      <ProCard>
        <ProTable<SysUserData, SysUserParams> {...tableProps}>
        </ProTable>
      </ProCard>
    </PageContainer>
  )
}
